<template>
  <view class="clickShowText" :style="takeStyle">
    <slot></slot>
    <view class="clickShowText_showBox base_box_round"
      :id="boxId"
      :style="'background:'+store.state.theme+';transform: translateX(calc('+boxLeft+'))'">
      {{props.text}}
    </view>
  </view>
</template>

<script setup>
import { computed, nextTick, onMounted, ref,watch  } from "vue"
import store from '@/store/index.js'

const props = defineProps({
  text: {
    type: String,
    default: '',
    validator: function(value) {
      return typeof value === 'string' || String(value);
    }
  },
  takeStyle: {
    type: Object,
    default: () => {}
  }
})

// 生成唯一ID
const boxId = ref(`box_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`)
const boxLeft = ref('-50%')
const screenWidth = computed(() => store.state.SystemInfo.screenWidth)

const takeBoxLeft = () => {
  // 使用 uni.createSelectorQuery() 获取元素信息
  const query = uni.createSelectorQuery()
  query.select(`#${boxId.value}`).boundingClientRect(rect => {
    if (!rect) return
    
    // 设置显示
    boxLeft.value = "-50%"
    
    // 检查左边界
    if (rect.left < 0) {
      boxLeft.value = -rect.left + "px - 50%"
    }
    
    // 检查右边界
    if (rect.right > screenWidth.value) {
      boxLeft.value = screenWidth.value - rect.right + "px - 50%"
    }
  }).exec()
}

// 监听文本变化
watch(() => props.text, () => {
  nextTick(() => {
    takeBoxLeft()
  })
})

// 组件挂载时
onMounted(() => {
  nextTick(() => {
    takeBoxLeft()
  })
})
</script>

<style lang="scss" scoped>
@import "@/style/base.scss";

.clickShowText {
  position: relative;
  width: max-content;
  
  .clickShowText_showBox {
    position: absolute;
    left: 50%;
    padding: 0.3em 0.5em;
    margin-top: 5rpx;
    z-index: 100;
    max-width: 80vw;
    word-wrap: break-word;
    opacity: 0; /* 初始设置为不可见 */
  }
  
  &:hover .clickShowText_showBox {
    opacity: 1; /* hover 时显示 */
  }
}
</style>